/*
 *所有关于materialfactoryplan类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*materialfactoryplanService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using DGZImp.Core.BaseProvider;
using DGZImp.Core.Extensions.AutofacManager;
using ATkg.BizAppProject.DomainModels;
using System.Linq;
using DGZImp.Core.Utilities;
using System.Linq.Expressions;
using DGZImp.Core.Extensions;

using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using ATkg.BizAppProject.IRepositories;
using DGZImp.Core.Exceptions;
using Newtonsoft.Json.Linq;
using System.Globalization;
using DGZImp.Core.EFDbContext;
using Microsoft.Extensions.Configuration;
using DocumentFormat.OpenXml.Wordprocessing;
using static ATkg.BizAppProject.Controllers.table_wgjyController;
using DGZImp.Core.DbSqlSugar;
using System.Xml.Linq;

namespace ATkg.BizAppProject.Services
{
    public partial class materialfactoryplanService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly ImaterialfactoryplanRepository _repository;//访问数据库
        public ISqlSugarClient Db = AutofacContainerModule.GetService<ServiceDbContext>()?.SqlSugarClient;
        public IConfiguration _config;
        public HttpClient client = null;
        public static IHttpClientFactory _httpClientFactory { get; set; }

        public AmesSyncService ames = AutofacContainerModule.GetService<AmesSyncService>();

        [ActivatorUtilitiesConstructor]
        public materialfactoryplanService(
            ImaterialfactoryplanRepository dbRepository,
            IHttpContextAccessor httpContextAccessor
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }

        public async Task<object> get_cailiao_gdplan()
        {
            DateTime now = DateTime.Now;
            string formattedTime = now.ToString("yyyy-MM-dd HH:mm:ss");
            // 安全转换（不抛异常）
            if (DateTime.TryParseExact(
                formattedTime,
                "yyyy-MM-dd HH:mm:ss",
                CultureInfo.InvariantCulture, // 忽略区域差异
                DateTimeStyles.None,
                out DateTime result_date))
            {
                Console.WriteLine($"转换成功: {result_date}");
            }
            else
            {
                Console.WriteLine("格式错误！");
            }
            Dictionary<string, string> weituo = new Dictionary<string, string>
                {
                    { "white", "倒角电镀" },
                    { "final", "检包" },
                };
            Dictionary<string, string> state = new Dictionary<string, string>
                {
                    { "draft", "新建" },
                    { "cancel", "取消" },
                    { "confirmed", "等待原材料" },
                    { "ready", "准备生产" },
                    { "in_production", "已开始生产" },
                };
            Console.WriteLine("进来了！！！");
            ames.userName = "duyang@atmcn.com";
            ames.password = "Du123456*";
            ames.url = "http://10.7.1.3/jsonrpc";
            ames.db = "atm";
            var qmain_ = new List<object>();
            qmain_.Add("powder");
            qmain_.Add("blank");
            var final_data_info1 = new List<object>();
            for (int i = 0; i < qmain_.Count; i++) {
                string per_ = qmain_[i].ToString();
                var qDomain = new List<object> {
                new List<object> { "production_type", "=","powder" },
                    "|",
                    "|",
                    new List<object> { "state", "=", "confirmed"},
                    new List<object> { "state", "=", "ready"},
                    new List<object> { "state", "=", "in_production"},
                };
                    var qFields = new List<string> {
                    "id", "state","schedule_id","name","raw_lot_id","steelgrade_id","product_id"
                };
                var qPage = new { };
                //var qPage = new { context = new { lang = "zh_CN", tz = "Asia/Shanghai", bin_size = true }, limit = 10000, offset = 0 };
                //var qPage12 = new { context = new { lang = "zh_CN", tz = "Asia/Shanghai", no_scrap = true }, limit = 10000, offset = 0 };
                var resp = await ames.Get_info_gzd("mrp.production", qDomain, qFields, qPage);
                if (resp.ContainsKey("error"))
                {
                    var message = $"【拉取单据】{resp["error"].ToString()}";
                    throw new AppException(message);
                }
                var res = (JArray)resp["result"];
                if (res == null || res.Count <= 0)
                {
                    return 0;
                }

                for(int j = 0; j < res.Count; j++)
                {
                    Console.WriteLine(res[j]);
                    List<object> per_info = new List<object>();
                    var per_info_list = res[j];
                    string schedule_id = per_info_list["schedule_id"] is JArray schedule_idArray
                        && schedule_idArray.Count > 1
                        ? schedule_idArray[1].ToString()
                        : string.Empty;
                    //var schedule_id = per_info_list["schedule_id"].ToString() == "false"? "": per_info_list["schedule_id"][1].ToString();
                    string raw_lot_id = per_info_list["raw_lot_id"] is JArray rawLotArray
                        && rawLotArray.Count > 1
                        ? rawLotArray[1].ToString()
                        : string.Empty;
                    string steelgrade_id = per_info_list["steelgrade_id"] is JArray steelgrade_idArray
                        && steelgrade_idArray.Count > 1
                        ? steelgrade_idArray[1].ToString()
                        : string.Empty;
                    //per_info.Add(per_info_list["steelgrade_id"].ToString() == "false" ? "" : per_info_list["steelgrade_id"][1].ToString());
                    string product_id = per_info_list["product_id"] is JArray product_idArray
                        && product_idArray.Count > 1
                        ? product_idArray[1].ToString()
                        : string.Empty;
                    //per_info.Add(per_info_list["product_id"].ToString() == "false" ? "" : per_info_list["product_id"][1].ToString());
                    per_info.Add(state[per_info_list["state"].ToString()]);
                    per_info.Add(schedule_id);
                    per_info.Add(per_info_list["name"]);
                    per_info.Add(raw_lot_id);
                    per_info.Add(steelgrade_id);
                    per_info.Add(product_id);
                    final_data_info1.Add(per_info);
                }
            }                
            return final_data_info1;
        }

        public static string ConvertUtcToBeijingTime(string utcTimeString)
        {
            // 1. 验证输入参数
            if (string.IsNullOrWhiteSpace(utcTimeString))
            {
                throw new ArgumentNullException(nameof(utcTimeString), "UTC时间字符串不能为空");
            }

            // 2. 定义时间格式
            string timeFormat = "yyyy-MM-dd HH:mm:ss";

            // 3. 解析UTC时间字符串
            if (!DateTime.TryParseExact(
                utcTimeString,
                timeFormat,
                CultureInfo.InvariantCulture,
                DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal,
                out DateTime utcTime))
            {
                throw new FormatException($"输入时间格式不正确，请使用'{timeFormat}'格式");
            }

            // 4. 转换为北京时间（UTC+8）
            DateTime beijingTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, TimeZoneInfo.FindSystemTimeZoneById("China Standard Time"));

            // 5. 格式化输出
            return beijingTime.ToString(timeFormat, CultureInfo.InvariantCulture);
        }

        public static double CalculateTimeDifferenceInHours(string timeStr1, string timeStr2, int timeType = 0)
        {
            // 1. 验证输入参数
            if (string.IsNullOrWhiteSpace(timeStr1))
                throw new ArgumentNullException(nameof(timeStr1), "第一个时间字符串不能为空");
            if (string.IsNullOrWhiteSpace(timeStr2))
                throw new ArgumentNullException(nameof(timeStr2), "第二个时间字符串不能为空");

            // 2. 定义时间格式
            string timeFormat = "yyyy-MM-dd HH:mm:ss";
            CultureInfo invariantCulture = CultureInfo.InvariantCulture;

            // 3. 解析时间字符串
            if (!DateTime.TryParseExact(timeStr1, timeFormat, invariantCulture, DateTimeStyles.None, out DateTime time1))
                throw new FormatException($"第一个时间格式不正确，请使用'{timeFormat}'格式");
            if (!DateTime.TryParseExact(timeStr2, timeFormat, invariantCulture, DateTimeStyles.None, out DateTime time2))
                throw new FormatException($"第二个时间格式不正确，请使用'{timeFormat}'格式");

            // 4. 根据时间类型转换为统一时区（UTC）
            switch (timeType)
            {
                case 1: // 均为UTC时间
                    time1 = DateTime.SpecifyKind(time1, DateTimeKind.Utc);
                    time2 = DateTime.SpecifyKind(time2, DateTimeKind.Utc);
                    break;
                case 2: // timeStr1为UTC，timeStr2为本地
                    time1 = DateTime.SpecifyKind(time1, DateTimeKind.Utc);
                    time2 = time2.ToUniversalTime(); // 本地转UTC
                    break;
                case 3: // timeStr1为本地，timeStr2为UTC
                    time1 = time1.ToUniversalTime(); // 本地转UTC
                    time2 = DateTime.SpecifyKind(time2, DateTimeKind.Utc);
                    break;
                default: // 均为本地时间（默认）
                    time1 = DateTime.SpecifyKind(time1, DateTimeKind.Local);
                    time2 = DateTime.SpecifyKind(time2, DateTimeKind.Local);
                    break;
            }

            // 5. 计算时间差（总毫秒数），转换为小时数
            TimeSpan difference = time1 - time2;
            double hours = difference.TotalHours;

            return Math.Round( hours,2);
        }

        public class caiplandata
        {
            [SugarColumn(IsPrimaryKey = true)] // 主键标识（若存在）
            public string DataModel { get; set; }
            public string DataYear { get; set; }
            public string DataYue { get; set; }
            public string DataRi { get; set; }
            public string DataInfo1 { get; set; }
            public string DataInfo2 { get; set; }
            public string DataInfo3 { get; set; }
            public string DataInfo4 { get; set; }

        }


        public async Task<object> get_cailiao_plan_data()
        {
            // 1. 获取当前北京时间（本地时间）
            DateTime now = DateTime.Now;

            // 2. 获取当前日期的前一天（例如今天2025-11-25，前一天是2025-11-24）
            DateTime yesterday = now.Date.AddDays(-1);

            // 3. 构建前一天的时间范围（00:00:00 到 23:59:59.9999999）
            DateTime startDate = yesterday; // 前一天的00:00:00
            DateTime stopDate = yesterday.AddDays(1).AddTicks(-1); // 前一天的23:59:59.9999999

            // 4. 转换为UTC时间
            DateTime startUtc = startDate.ToUniversalTime();
            DateTime stopUtc = stopDate.ToUniversalTime();
            string year = "";
            string monthPadded = "";
            string dayPadded = "";
            
            // 格式化输出
            string startData = startUtc.ToString("yyyy-MM-dd HH:mm:ss");
            string stopData = stopUtc.ToString("yyyy-MM-dd HH:mm:ss");
            //string startData = "2025-11-01 16:00:00";
            //string stopData = "2025-11-02 15:59:59";

            string now_time = ConvertUtcToBeijingTime(startData);
            string format = "yyyy-MM-dd HH:mm:ss";
            if (DateTime.TryParseExact(now_time, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime dateTime))
            {
                // 提取年、月、日，并转换为字符串
                year = dateTime.Year.ToString();
                string month = dateTime.Month.ToString();
                string day = dateTime.Day.ToString();
                // 如果需要两位数的月份和日期（例如 "03" 而不是 "3"），可以使用格式化输出
                monthPadded = dateTime.Month.ToString("D2");
                dayPadded = dateTime.Day.ToString("D2");
            }
            else
            {
                Console.WriteLine("日期字符串格式不正确，无法解析。");
            }
            // 构建最终结构
            var result = new List<List<object>>
            {
                new List<object> { "date_stock_done", ">=", startData },
                new List<object> { "date_stock_done", "<=", stopData }
            };
            // 打印结果
            foreach (var item in result)
            {
                Console.WriteLine($"[{string.Join(", ", item)}]");
            }
            Console.WriteLine("进来了！！！");
            ames.userName = "duyang@atmcn.com";
            ames.password = "Du123456*";
            ames.url = "http://10.7.1.3/jsonrpc";
            ames.db = "atm";

            var qDomain = new List<object> {
                    new List<object> { "date_stock_done", ">=", startData},
                    new List<object> { "date_stock_done", "<=", stopData}
                };
            var qFields = new List<string> {
                    "id", "blank_lot_id","date_stock_done","date_blank_register","date_p2_done","date_issue",
                };
            var qPage = new { };
            var resp = await ames.Get_info_gzd("mrp.production.report.blank", qDomain, qFields, qPage);
            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];
            Console.WriteLine(res);
            var list_insert_db = new List<caiplandata>();
            if (res.Count <= 0)
            {
                var result_re0 = Db.Queryable<caiplandata>()
                .Where(it => it.DataYear == year && it.DataYue == monthPadded && it.DataRi == dayPadded)
                .Select(m => new
                {
                    m.DataYear,
                    m.DataYue,
                    m.DataRi,
                })
                .ToList();
                if (result_re0.Count == 0)
                {
                    var data_3 = new caiplandata
                    {
                        //DataModel = name,s
                        DataYear = year,
                        DataYue = monthPadded,
                        DataRi = dayPadded,
                        DataInfo1 = "0",
                        DataInfo2 = "0",
                        DataInfo3 = "0",
                        DataInfo4 = "0",
                    };
                    list_insert_db.Add(data_3);
                    await Db.DoInsertAsync<caiplandata>(list_insert_db);
                }
                return 0;
            }
            else
            {
                int count_ = res.Count;
                double all_time = 0.0;
                double mp_yxsj = 0.0;
                double yxsj_cpf = 0.0;
                double cpf_hj = 0.0;

                for (int i = 0; i < res.Count; i++)
                {
                    var per_ = res[i];
                    string name = per_["blank_lot_id"][1].ToString();
                    string mp_ruku = ConvertUtcToBeijingTime(res[i]["date_stock_done"].ToString());
                    string yxsj_chanchu = ConvertUtcToBeijingTime(res[i]["date_blank_register"].ToString());
                    string cpf_cl = ConvertUtcToBeijingTime(res[i]["date_p2_done"].ToString());
                    string hj_chuku = ConvertUtcToBeijingTime(res[i]["date_issue"].ToString());
                    //Console.WriteLine(name);
                    //Console.WriteLine(mp_ruku);
                    //Console.WriteLine(yxsj_chanchu);
                    //Console.WriteLine(cpf_cl);
                    //Console.WriteLine(hj_chuku);
                    //Console.WriteLine("1111111111111111111111111111");
                    //var qDomain_zl = new List<object> {
                    //    new List<object> { "lot_id", "ilike", name},
                    //};
                    //var qFields_zl = new List<string> {
                    //    "id", "begin_time"
                    //};
                    //var qPage_zl = new { };
                    //var resp_zhil = await ames.Get_info_gzd("quality.point", qDomain_zl, qFields_zl, qPage);
                    //Console.WriteLine(resp_zhil);
                    //var res_zl = (JArray)resp_zhil["result"];
                    //Console.WriteLine(res_zl);
                    //string zhiliang_time = ConvertUtcToBeijingTime(res_zl[0]["begin_time"].ToString());
                    //Console.WriteLine(zhiliang_time);

                    all_time += CalculateTimeDifferenceInHours(mp_ruku, hj_chuku);
                    mp_yxsj += CalculateTimeDifferenceInHours(mp_ruku, yxsj_chanchu);
                    //double zhil_yxsj = CalculateTimeDifferenceInHours(zhiliang_time, yxsj_chanchu);
                    yxsj_cpf += CalculateTimeDifferenceInHours(yxsj_chanchu, cpf_cl);
                    cpf_hj += CalculateTimeDifferenceInHours(cpf_cl, hj_chuku);
                    //Console.WriteLine("44444444444444");
                    //Console.WriteLine(all_time);
                    //Console.WriteLine(mp_yxsj);
                    ////Console.WriteLine(zhil_yxsj);
                    //Console.WriteLine(yxsj_cpf);
                    //Console.WriteLine(cpf_hj);
                    //Console.WriteLine("55555555555555");
                    //string a = "2025-11-24 14:11:13";               

                }
                var result_re = Db.Queryable<caiplandata>()
                    .Where(it => it.DataYear == year && it.DataYue == monthPadded && it.DataRi == dayPadded)
                    .Select(m => new
                    {
                        m.DataYear,
                        m.DataYue,
                        m.DataRi,
                    })
                    .ToList();
                if (result_re.Count == 0)
                {
                    var data_3 = new caiplandata
                    {
                        DataYear = year,
                        DataYue = monthPadded,
                        DataRi = dayPadded,
                        DataInfo1 = Math.Round(all_time / count_, 2).ToString(),
                        DataInfo2 = Math.Round(mp_yxsj / count_, 2).ToString(),
                        DataInfo3 = Math.Round(yxsj_cpf / count_, 2).ToString(),
                        DataInfo4 = Math.Round(cpf_hj / count_, 2).ToString(),
                    };
                    list_insert_db.Add(data_3);
                    await Db.DoInsertAsync<caiplandata>(list_insert_db);
                }
                return list_insert_db;
            }
            
        }

        public async Task<object> get_cailiao_plan_data_from_db()
        {
            // 1. 获取当前北京时间（本地时间）
            DateTime now = DateTime.Now;
            // 格式化输出
            string today = now.ToString("yyyy-MM-dd HH:mm:ss");
            string now_time = ConvertUtcToBeijingTime(today);
            string format = "yyyy-MM-dd HH:mm:ss";
            string year = "";
            string monthPadded = "";
            string dayPadded = "";
            // 尝试解析字符串
            if (DateTime.TryParseExact(now_time, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime dateTime))
            {
                // 提取年、月、日，并转换为字符串
                year = dateTime.Year.ToString();
                string month = dateTime.Month.ToString();
                string day = dateTime.Day.ToString();
                // 如果需要两位数的月份和日期（例如 "03" 而不是 "3"），可以使用格式化输出
                monthPadded = dateTime.Month.ToString("D2");
                dayPadded = dateTime.Day.ToString("D2");
            }
            else
            {
                Console.WriteLine("日期字符串格式不正确，无法解析。");
            }
            var result_re = Db.Queryable<caiplandata>()
                .Where(it => it.DataYear == year && it.DataYue == monthPadded)
                .Select(m => new
                {
                    m.DataYear,
                    m.DataYue,
                    m.DataRi,
                    m.DataInfo1,
                    m.DataInfo2,
                    m.DataInfo3,
                    m.DataInfo4
                })
                .ToList();     
            return result_re;
        }
    }
}